<?php
namespace ac\controllers;

use Yii;
use ac\controllers\BasicController;
use app\models\Admin;
use ac\component\tool\Tool;
use ac\component\tool\ValidateCode;
use ac\component\exception\ErrMap;
use app\models\OperationLog;
use app\models\Areas;


class PublicController extends BasicController
{
    public $layout = false;

	/*登录*/
    public function actionLogin()
    {
        if(Yii::$app->request->isPost){
            /*查看验证码*/
            $vaildateCode = $this->session->get('vaildate_code');
            // P($vaildateCode);
            if(empty($vaildateCode) or (strtolower($vaildateCode) != strtolower($this->post["Admin"]["checkcode"]))){
                $this->session->remove('vaildate_code');
                list($errno, $errmsg) = ErrMap::getError(10008);
                $exception = '';
            }else{
                $this->post = Yii::$app->request->post();
                // P($this->post);
                $admin = new Admin;
                if($admin->login($this->post)){
                    $userInfo = Yii::$app->session->get('loginInfo')->userInfo;
                    // P($userInfo);
                    $args = array(
                        'loginid' => $userInfo['admin_id'],
                        'loginname' => $userInfo['username'],
                        'back_code' => 0,
                        'back_info' => '登录成功'
                    );
                    /*返回前台的登录数据*/
                    $uinfo = array(
                        'username' => $userInfo['username'],
                        'avatar' => $userInfo['avatar'],
                        'issuper' => $userInfo['issuper'],
                        // 'permissions' => Yii::$app->session->get('loginInfo')->permissions,
                    );
                    // P($uinfo);
                    if(gettype($res = OperationLog::addLog($args, '', $uinfo)) != 'boolean'){//操作日志
                        return $res;
                    };
                }else{
                    if($admin->hasErrors()){
                        // P($admin->getErrors());
                        list($errno, $errmsg) = ErrMap::getError(10009);
                        $exception = $admin->getErrors();
                        if(array_key_exists("accountDisable", $exception)){
                            list($errno, $errmsg) = ErrMap::getError(10005, '该账户未启用');//返回信息
                        };
                        if(array_key_exists("enterpriseDisable", $exception)){
                            list($errno, $errmsg) = ErrMap::getError(10005, '该企业未启用');//返回信息
                        };
                        if(array_key_exists("weekDisable", $exception)){
                            list($errno, $errmsg) = ErrMap::getError(10005, '周'. date("w") .'不允许登录');//返回信息
                        };
                    }
                }
            }
            $args = array(
                'loginid' => 0,
                'loginname' => isset($this->post['Admin']['username'])?$this->post['Admin']['username']:'',
                'back_code' => $errno,
                'back_info' => $errmsg,
            );
            // P($args);
            if(gettype($res = OperationLog::addLog($args, $exception)) != 'boolean'){//操作日志
                return $res;
            };

        };
        list($errno, $errmsg) = ErrMap::getError(10005);
        $args = array(
            'loginid' => 0,
            'loginname' => '',
            'back_code' => $errno,
            'back_info' => $errmsg,
        );
        if(gettype($res = OperationLog::addLog($args)) != 'boolean'){//操作日志
            return $res;
        };
    }

    /*登出*/
    public function actionLogout()
    {
        Yii::$app->session->removeAll();
        if(Yii::$app->session->get('loginInfo') === null){
            return Tool::showRes([0, '成功登出']);
        }else{
            return Tool::showRes(ErrMap::getError(10006));
        }
    }


    /*验证码*/
    public function actionCreateCode()
    {
        Yii::$app->response->send();//防止报错 Headers already sent in......
        $session = Yii::$app->session;
        $session -> remove('vaildate_code');
        $code = new ValidateCode();
        $code -> doimg();
        $session -> set('vaildate_code', $code -> getCode());
    }

    /*取出所有省数据*/
    public function actionGetProvinceList()
    {
        $list = Areas::getProvinceList();
        return Tool::showRes([0, '获取成功'], $list);
    }

    /*取出 市 数据 根据省ID*/
    public function actionGetCityByProvince()
    {
        $provinceid = $this->get['id'];
        $list = [];
        if($provinceid){
            $list = Areas::getCityByProvince($provinceid);
        }
        return Tool::showRes([0, '获取成功'], $list);
    }

    /*取出 区 数据 根据市ID*/
    public function actionGetDistrictByCity()
    {
        $cityid = $this->get['id'];
        $list = [];
        if($cityid){
            $list = Areas::getDistrictByCity($cityid);
        }
        return Tool::showRes([0, '获取成功'], $list);
    }

    /*百度编辑器验证*/
    public function actionUeditor()
    {
        return '{}';
    }


    /*error*/
    public function actionError()
    {
        P($_SERVER);
    }

    /*test*/
    public function actionTest()
    {
        phpinfo();die;
        $time = time();
        $token = Yii::$app->jwt->getBuilder()
                ->issuedBy('http://jiang.com')
                ->permittedFor('http://jiang.org')
                ->identifiedBy('4f1g23a12aa', true)
                ->issuedAt($time)
                ->canOnlyBeUsedAfter($time + 60)
                ->expiresAt($time + 3600)
                ->withClaim('uid', 1)
                ->getToken();


        $token->getHeaders();
        $token->getClaims();

        echo $token->getHeader('jti');
        echo '<br>';
        echo $token->getClaim('iss');
        echo '<br>';
        echo $token->getClaim('uid');
        echo '<br>';
        echo $token;
        echo '<br>';
        echo '==========================================================';
        echo '<br>';

        // $token2 = "asdf5a4sf35asf";
        $token = Yii::$app->jwt->getParser()->parse((string) $token);
        $token->getHeaders();
        $token->getClaims();

        echo $token->getHeader('jti');
        echo '<br>';
        echo $token->getClaim('iss');
        echo '<br>';
        echo $token->getClaim('uid');
        echo '<br>';
        echo '==========================================================';
        echo '<br>';

        $data = Yii::$app->jwt->getValidationData();
        $data->setIssuer('http://example.com');
        $data->setAudience('http://example.org');
        $data->setId('4f1g23a12aa');

        var_dump($token->validate($data));
        echo '<br>';

        $data->setCurrentTime(time() + 61);
        var_dump($token->validate($data));
        echo '<br>';

        $data->setCurrentTime(time() + 4000);
        var_dump($token->validate($data));
        echo '<br>';
        echo '==========================================================';
        echo '<br>';


        $dataWithLeeway = Yii::$app->jwt->getValidationData();
        $dataWithLeeway->setIssuer('http://example.com');
        $dataWithLeeway->setAudience('http://example.org');
        $dataWithLeeway->setId('4f1g23a12aa');

        var_dump($token->validate($dataWithLeeway));
        echo '<br>';

        $dataWithLeeway->setCurrentTime($time + 61);
        var_dump($token->validate($dataWithLeeway));
        echo '<br>';
        
        $dataWithLeeway->setCurrentTime($time + 3610);
        var_dump($token->validate($dataWithLeeway));
        echo '<br>';
        
        $dataWithLeeway->setCurrentTime($time + 4000);
        var_dump($token->validate($dataWithLeeway));
        echo '<br>';
        echo '==========================================================';
        echo '<br>';

        $jwt = Yii::$app->jwt;
        $signer = $jwt->getSigner('HS256');
        $key = $jwt->getKey('123r');
        $time = time();

        $token = $jwt->getBuilder()
                    ->issuedBy('http://example2.com')
                    ->permittedFor('http://example2.org')
                    ->identifiedBy('4f1g23a12aa', true)
                    ->issuedAt($time)
                    ->canOnlyBeUsedAfter($time + 60)
                    ->expiresAt($time + 3600)
                    ->withClaim('uid', 12)
                    ->withClaim('name', 'jiang')
                    ->getToken($signer, $key);
        echo $token;
        echo '<br>';
        var_dump($token->verify($signer, 'testing 1'));
        echo '<br>';
        var_dump($token->verify($signer, 'testing'));
        echo '<br>';
        var_dump($token->verify($signer, '123r'));
        echo '<br>';
        echo '==========================================================';
        echo '<br>';

        // $jwt = Yii::$app->jwt;
        // $signer = $jwt->getSigner('RS256');
        // $privateKey = $jwt->getKey('123');
        // $time = time();

        // $token = $jwt->getBuilder()
        //             ->issuedBy('http://example.com')
        //             ->permittedFor('http://example.org')
        //             ->identifiedBy('4f1g23a12aa', true)
        //             ->issuedAt($time)
        //             ->canOnlyBeUsedAfter($time + 60)
        //             ->expiresAt($time + 3600)
        //             ->withClaim('uid', 1)
        //             ->getToken($signer, $key);
            
        // $publicKey = $jwt->getKey('/jwt.txt');

        // var_dump($token->verify($signer, $publicKey));
        // echo '<br>';
        // echo '==========================================================';

    }
    
}
